#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTimer>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("主窗体");

    currentStatus.status.store(MU_STATUS_NOTRUN);

    DeviceControl::GetInstance()->initialDevice();

    QTimer::singleShot(2,this,[=](){

        QLabel *permanent=new QLabel(this);
        permanent->setText(QString::fromStdString(DateTime::getClock() +"\t"+ currentStatus.curVer));
        ui->statusbar->addPermanentWidget(permanent);//显示永久信息
    });
    initMembers();
    initUIs();
    reflushUI();    // 刷新pos及轴信息

//    auto result = std::async(std::launch::async,[this](){
//        importALL();
//    });
    //result.get();

}

MainWindow::~MainWindow()
{
    delete ui;
}







void MainWindow::PosToUI(RobotPos pos,RobotAxle axis)
{
    ui->lb_x->setText(QString::number(pos.x));
    ui->lb_y->setText(QString::number(pos.y));
    ui->lb_z->setText(QString::number(pos.z));
    ui->lb_a->setText(QString::number(pos.a));
    ui->lb_b->setText(QString::number(pos.b));
    ui->lb_c->setText(QString::number(pos.c));

    ui->lb_rx->setText(QString::number(axis.a1));
    ui->lb_ry->setText(QString::number(axis.a2));
    ui->lb_rz->setText(QString::number(axis.a3));
    ui->lb_ra->setText(QString::number(axis.a4));
    ui->lb_rb->setText(QString::number(axis.a5));
    ui->lb_rc->setText(QString::number(axis.a6));
}

void MainWindow::initUIs()
{
    initToolBar();
    curMouse = new QLabel;
    curMouse->setStyleSheet(" QLineEdit{ color: green }");

    statusBar()->addWidget(curMouse);


    creatCameraTools();


    for(auto in:MU_Messages::All){
        if(in != "预留"){
            statusWidget.insert(QString::fromStdString(in),new BodyWidget(QString::fromStdString(in)));
            ui->seam_layout->addWidget(statusWidget[QString::fromStdString(in)]);
        }

    }
    // 首次需要手动触发界面UI刷新
    for(MU_DEVICE_I i = MU_DEVICE_NONE;i<MU_DEVICE_ALL;++i){
        auto type = currentStatus.GetInitType(i);
        QString in = QString::fromStdString(MU_Messages::All.at(i));
        if(in != "预留")
        statusWidget[in]->setStatus(type);
    }

    ui->stackedWidget->addWidget(paraMentView);     // 1
    ui->stackedWidget->addWidget(seamView);         // 2
    ui->stackedWidget->addWidget(&debugForm);       // 3
    ui->stackedWidget->addWidget(&connectForm);       // 4


    this->tabifyDockWidget(ui->dw_Diagnosis,ui->dw_deviceS);
    this->tabifyDockWidget(ui->dw_warn,ui->dw_real);
    this->tabifyDockWidget(ui->dw_exp,ui->dw_image);
    //seamTask->show();

}

/**
 * @brief MainWindow::initToolBar
 * @details 初始化工具栏，添加图标等
 */
void MainWindow::initToolBar()
{
    controlBar  = new QToolBar(this);
    controlBar->setLayoutDirection(Qt::RightToLeft);

    controlBar->setIconSize(QSize(36, 36));
    controlBar->addSeparator();
    controlBar->addAction(ui->actionLink);
    controlBar->addSeparator();
    controlBar->addAction(ui->action3D);
    controlBar->addSeparator();
    controlBar->addAction(ui->actionImg);
    controlBar->addSeparator();
    controlBar->addAction(ui->actionView);
    controlBar->addSeparator();
    controlBar->addAction(ui->actionChart);
    controlBar->addSeparator();
    controlBar->addAction(ui->actionDebug);
    controlBar->addSeparator();
    controlBar->addAction(ui->actionWeldPara);
    controlBar->addSeparator();
    controlBar->addAction(ui->actionCleanTask);
    controlBar->addSeparator();
    //controlBar->addAction(ui->actionOpenDebug);

    this->addToolBar(Qt::TopToolBarArea, controlBar);
}

/**
 * @brief MainWindow::creatCameraTools
 * @details 主要功能维创建了相机的格点或辅助线功能
 */
void MainWindow::creatCameraTools()
{
    ui->camDis->addWidget(dis,8);

    QRadioButton *help = new QRadioButton;
    QRadioButton *gridButton = new QRadioButton;
    QRadioButton *clean = new QRadioButton;
    QGridLayout *alyout = new QGridLayout;
//    help->setChecked(true);
//    gridButton->setChecked(true);
    clean->setChecked(true);

    help->setText("其他辅助线");
    help->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);//设置组件大小可扩展
    alyout->setSpacing(10);//设置间距
    gridButton->setText("格点辅助线");
    gridButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);//设置组件大小可扩展
    clean->setText("所有不显示");
    clean->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);//设置组件大小可扩展
    // alyout->setRowStretch(1,1);
    alyout->addWidget(help,0,0);
    alyout->addWidget(gridButton,0,1);
    alyout->addWidget(clean,0,2);

    QButtonGroup *buttonGroup = new QButtonGroup;
    buttonGroup->addButton(help);
    buttonGroup->addButton(gridButton);
    buttonGroup->addButton(clean);
    connect(buttonGroup, QOverload<int>::of(&QButtonGroup::buttonClicked),
          [=](int id){
            id = abs(id)-2;
            if(0 == id){    //其他辅助线
                auxiliary.exchange(1);
            }else if(1==id){
                auxiliary.exchange(2);
            }else{
                auxiliary.exchange(0);
            }
            qDebug()<<id<<"\t"<<auxiliary.load();
    });


    ui->camDis->addLayout(alyout,0);
//    ui->camDis->setStretch(0,8);
}

void MainWindow::reflushUI()
{
    QTimer::singleShot(2000,this,[=](){
        std::thread *back = new std::thread([this](){
            static int errCount = 0;
            while (getSystemStatus()) {
                    while(2000 > errCount){
                        if(currentStatus.GetInit(MU_DEVICE_ROBOT)){ // 如果机器人初始化成功
                            auto pos = RobotHelper::GetInstance()->_robot->getCurrPos(RobotTCP::UPLOAD);
                            PosToUI(pos,RobotHelper::GetInstance()->_robot->getCurrAxle());
                        }else {
                            sleep_s(3);
                        }
                        // 当相机ok
                        if(camShow.load() && currentStatus.GetInit(MU_DEVICE_CAM)){
                            auto mat = CameraHelper::GetInstance()->GetPictrue();
                            if(!mat.empty()) {
                                // if(auxiliary)
                                dis->display(mat);
                            }
                            else{
                                errCount++;
                                pushWarn(MU_Messages::Camera,MU_EXPS::EXP_CAMERA_GETBUFFER,MU_ERROR_MODULE_CAM);
                            }
                        }
                        sleep_ms(50);
                    }
                    sleep_s(20);
            }
            qWarning()<<BOLDYELLOW<<"系统停止刷新POS信息!"<<"\t"<<RESET;
        });

        /// 线程池添加后台刷新常驻线程
        ThreadPool::GetInstance()->pushPermanentAsync(MU_THREAD_UPDATE,back);
    });
}

void MainWindow::initMembers()
{
    paraMentView = new ParaView;    /* 创建参数显示窗体 */
    seamView  =    new  SeamWeldForm;// 焊接参数调整界面
    localView = new LocalPara;      // 本地参数调整界面
    dis         = new QCvDisplay;           /* 创建相机显示窗体 */

    AppManager::GetInstance()->reportExp.connect([this](std::string str){
        ui->exp_Browser->append(QString::fromStdString(str));
    });
    AppManager::GetInstance()->reportWarn.connect([this](std::string str){
        ui->warn_Browser->append(QString::fromStdString(str));
    });

    connect(ui->actionOpenDebug,&QAction::triggered,[this](){debugForm.show();});
    connect(ui->actionAbout,&QAction::triggered,[this](){aboutForm.sync();aboutForm.show();});

    connect(dis,&QCvDisplay::sig_MouseMove,[this](QPoint pp){
        curMouse->setText("(" + QString::number(pp.rx())  + "," + QString::number(pp.ry())  + ")");
    });

    /**
     * @brief TurnOff
     * @details 当设备掉线及上线的时候通知到UI界面进行反馈刷新
     */
    currentStatus.deviceChanged.connect([this](MU_DEVICE_I index){
        auto type = currentStatus.GetInitType(index);
        QString in = QString::fromStdString(MU_Messages::All.at(index));
        if(in != "预留")
        statusWidget[in]->setStatus(type);
    });

}

void MainWindow::on_actionView_triggered()
{
    // paraMentView->show();
    ui->stackedWidget->setCurrentIndex(1);

}

void MainWindow::on_actionStartGrab_toggled(bool arg1)
{
    camShow.exchange(arg1);     /* 转换相机的显示状态 */
}

void MainWindow::on_actionWeldPara_triggered()
{
    ui->stackedWidget->setCurrentIndex(2);
}

void MainWindow::on_action3D_triggered()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::on_actionImg_triggered()
{
    ui->stackedWidget->setCurrentIndex(0);
}

/**
 * @brief MainWindow::on_actionDebug_toggled
 * @details 调试软件需要打开
 */
void MainWindow::on_actionDebug_triggered()
{
    ui->stackedWidget->setCurrentIndex(3);
}

// 设备链接登录模块
void MainWindow::on_actionLink_triggered()
{
    ui->stackedWidget->setCurrentIndex(4);
}


void MainWindow::on_actionOpenDebug_triggered()
{
    debugForm.show();
}

void MainWindow::on_actionLocalPara_triggered()
{
    localView->setAttribute(Qt::WA_ShowModal, true);
    localView->show();
}

void MainWindow::on_actionChart_triggered()
{
    cv::Mat g = cv::imread("rundata/img-bak/1.png");
    dis->showFull(true);
    //dis->setFixedSize(QSize(g.rows,g.cols));
    dis->setFixedSize(QSize(720,540));
    dis->display(g);
}

/**
 * @brief MainWindow::on_actionCleanTask_triggered
 * @details 清空任务
 */
void MainWindow::on_actionCleanTask_triggered()
{
    statusWidget["PLC"]->setStatus(MU_TY_STOP);
    cv::Mat g = cv::imread("rundata/img-bak/444.png");
//    dis->showFull(true);
//    dis->setFixedSize(QSize(g.rows,g.cols));
    dis->display(g);
//    std::thread([=](){
//        while(1){
//            LaserHelper::GetInstance()->Open();
//            LaserHelper::GetInstance()->Open();
//            qDebug()<<"我能继续打印";
//            sleep_s(2);
//        }
//    }).detach();

    pushWarn("系统长时间无法进入完成状态!",MU_ERROR_MODULE_APP);
    pushExp(MU_Messages::App,MU_EXPS::EXP_APP_INIT_FALSE,MU_ERROR_MODULE_APP);
}

void MainWindow::on_actionOpenLaser_triggered(bool checked)
{
    if(checked){
        LaserHelper::GetInstance()->Open();
    }else{
        LaserHelper::GetInstance()->Close();
    }
}

void MainWindow::on_actionExit_triggered()
{
    QMessageBox:: StandardButton result= QMessageBox::information(NULL, "退出程序",
                              "是否退出程序?", QMessageBox::Yes|QMessageBox::No);
    switch (result)
    {
    case QMessageBox::Yes:
        qApp->exit(0);
        break;
    case QMessageBox::No:
        break;
    default:
        break;
    }
}

//void MainWindow::on_actionOpenLaser_triggered()
//{
////    static bool checked = false;
////    if(checked){
////        LaserHelper::GetInstance()->Open();
////    }else{
////        LaserHelper::GetInstance()->Close();
////    }
//}

// 机器人诊断
void MainWindow::on_pb_Diagnosis_clicked()
{
    auto ff = string("8888888");
    auto gddfgf = SQLBase::prepare("INSERT INTO CAD (CADID,MIDPOINT) ",ff,"45464879");
    SQLHelper::GetBlade()->_p_tr->Exec(gddfgf);

    qDebug()<<gddfgf.c_str();

}
